#include <hl7.hpp>
#include <hl7/common.hpp>
#include <hl7/except.hpp>

#include <cassert>

int
main(int argc, char **argv)
{
    using namespace std;
    using namespace hl7;
    cout.setf(ios::boolalpha);

    if(argc == 2)
    {
        ifstream file;
        file.open(argv[1], ios::in|ios::binary|ios::ate);

        if (file.is_open())
        {
            char * memblock;
            ifstream::pos_type size = file.tellg();
            memblock = new char [size];

            file.seekg (0, ios::beg);
            file.read (memblock, size);
            file.close();

            string msg(memblock);
            delete [] memblock;

            try
            {
                /* Create a message object. */
                message m(msg);

                /* Break it into segments.*/
                m.parse();

                assert(m.contains("MSH"));
                assert(m.contains("PID"));

                /* Get a vector of the segment names. */
                vector<string> flds;
                flds = m.segments(flds);

                /* Print them out. */
                for(vector<string>::iterator iter = flds.begin(); iter != flds.end(); iter++)
                    cout << "'"<<(*iter)<<endl;


                /* Print out the entire PID segment. This is, in effect, 
                 * printing out message["PID"].hl7segment[0].segment.
                 */
                cout << m["PID"] <<endl;

                /* Since one can have multiple entries of a segment type, */
                /* segments are indexed from zero. Print out field 
                 * PID field 5. 
                 */

                cout << m["PID"][0][5] <<endl;

                if(!m.contains("GT1"))
                {
                    /* Create a new segment. */
                    vector<string> newseg;
                    string *gt1= new string("GT1|1|12345|Public^Jane^Q^^^||1234 Testing Ln.^GUA Line 2^Testville^TX^12345^US^^^^^|(555)555-5555^PRN^PH|(555)555-5555^WPN^PH|||||111-22-4433|||||^^^^^US^^^^^|||1- Employed full time|||||||||||||||||||||||||||||||||||");

                    newseg = util::split(*gt1, '|', newseg);
                    m.push("GT1", newseg);
                    delete gt1;

                    assert(m.contains("GT1"));
                    cout << m.contains("GT1") << endl;

                    flds = m.segments(flds);

                    for(vector<string>::iterator iter = flds.begin(); iter != flds.end(); iter++)
                        cout << "'"<<(*iter)<<"'" << endl;

                    cout << m["GT1"][0][0] << endl;
                }

            }
            catch(Exception &e)
            {
                cout << e.what() << endl;
            }
        }
    } 
    return EXIT_SUCCESS;
}
